package com.kyle.redpacket.service;

import com.kyle.redpacket.dao.entity.RedPacket;
import com.kyle.redpacket.dao.entity.RedRecord;
import com.kyle.redpacket.dao.repository.RedPacketRepository;
import com.kyle.redpacket.dao.repository.RedRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

/**
 * @author: zhonglinsen
 * @date: 2019/3/18
 */
@Service
@EnableAsync
public class RedServiceImpl implements IRedService {
    @Autowired
    RedRecordRepository redRecordRepository;

    @Autowired
    RedPacketRepository redPacketRepository;

    @Override public Optional<RedPacket> getRedPacket(String timestamp){
        RedPacket redPacket=new RedPacket();
        redPacket.setRedId(timestamp);
        return redPacketRepository.findOne(Example.of(redPacket));
    }

    /**
     * 发红包记录，异步的方式
     *
     * @param dto
     * @param list
     * @throws Exception
     */
    @Override
    @Async
    @Transactional(rollbackOn = Exception.class)
    public void recordRedPacket(RedPacket dto, List<RedRecord> list) throws Exception {
        redPacketRepository.save(dto);
        redRecordRepository.saveAll(list);
    }

    /**
     * 抢红包记录
     */
    @Override
    @Async
    public void recordRobRedPacket(Long userId, RedRecord order) throws Exception {
        redRecordRepository.findOne(Example.of(order))
                .ifPresent(redRecord1 -> {
                    redRecord1.setUserId(userId);
                    redRecordRepository.saveAndFlush(redRecord1);
                });
    }
}











